﻿using DbMapper.controller;
using DbMapper.model;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;

namespace DbMapper.view {
    public partial class MainWindow : Form {
        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
        public const int WM_CLOSE = 0x10;

        TabPage tabPage;
        RichTextBox richtextbox;
        System.Timers.Timer myTimer;
        static string sqlitestring = "";
        service.SQLHelper sqlHelper = new service.SQLHelper();

        service.SQLiteDBHelper sqllitehelper = new service.SQLiteDBHelper(sqlitestring);

        MainWindowController mainWindowController = new MainWindowController();



        public MainWindow() {
            InitializeComponent();
        }

        #region //页面加载
        private void MainWindow_Load(object sender, EventArgs e) {

            int pagenumber = 0;

            // 读取规则
            string path = AppDomain.CurrentDomain.BaseDirectory + "mapper.txt";
            string path2 = AppDomain.CurrentDomain.BaseDirectory + "reocrd.txt";
            //第一步读取配置文件

            FileStream file = new FileStream(path, FileMode.Open);
            StreamReader sr = new StreamReader(file, Encoding.UTF8);
            string strLine = sr.ReadToEnd();
            // 关闭文件
            sr.Close();
            file.Close();

            List<Record> recordlist = new List<Record>();
            FileStream file2 = new FileStream(path2, FileMode.Open);
            StreamReader sr2 = new StreamReader(file2, Encoding.UTF8);
            string strLine2 = sr2.ReadToEnd();
            // 关闭文件
            sr2.Close();
            file2.Close();
            //页面加载时：讲规则赋值到页面上
            foreach (TabPage page in tabControls.TabPages) {
                foreach (Control control in page.Controls) {
                    pagenumber++;
                    if (control is RichTextBox && pagenumber == 1) {

                        ((RichTextBox)control).Text = strLine;

                    } else {
                        ((RichTextBox)control).Text = strLine2;
                    }
                }
            }

            myTimer = new System.Timers.Timer(2000);//定时周期2秒
            myTimer.Elapsed += ImportData;//到2秒了做的事件
            myTimer.AutoReset = true; //是否不断重复定时器操作
            btn_close.Visible = false;

           btn_Import_Click(null, null);







        }
        #endregion

        #region //点击开始按钮，创建定时器。
        private void btn_Import_Click(object sender, EventArgs e) {

            //ImportData(null,null);

            var inputtimevalue = tb_inputtime.Text.Trim();

            int timevalue = Convert.ToInt32(inputtimevalue);

            int originvalue = timevalue * 1000;

            myTimer = new System.Timers.Timer(originvalue);//定时周期2秒
            myTimer.Elapsed += ImportData;//到2秒了做的事件
            myTimer.AutoReset = true; //是否不断重复定时器操作
            btn_close.Visible = false;
            myTimer.Enabled = true; //定时器开始用
                                    //如果不写下面这句会有一个异常。
                                    //异常：线程间操作无效: 从不是创建控件"richtextbox"的线程访问它
                                    //但这不是最好的方法。如果只有一个进程调用richtextbox而已。就可以用下面这句
                                    //如果有多个线程调用richtextbox等控件。就要用委托。具体百度
                                    //一篇参考博客http://www.cnblogs.com/zyh-nhy/archive/2008/01/28/1056194.html
            Control.CheckForIllegalCrossThreadCalls = false;
            btn_Import.Visible = false;
            btn_close.Visible = true;

        }
        #endregion

        #region//获取用户输入的匹配规则，转化成mapper,导入。
        public void ImportData(object sender, System.Timers.ElapsedEventArgs e) {
            #region   SQLSERVER 对SQLSERVER 版本
            string path = AppDomain.CurrentDomain.BaseDirectory + "mapper.txt";
            string path2 = AppDomain.CurrentDomain.BaseDirectory + "reocrd.txt";
            //第一步读取配置文件
            FileStream file = new FileStream(path, FileMode.Open);
            StreamReader sr = new StreamReader(file, Encoding.UTF8);
            string strLine = sr.ReadToEnd();
            // 关闭文件
            sr.Close();
            file.Close();

            List<Record> recordlist = new List<Record>();
            FileStream file2 = new FileStream(path2, FileMode.Open);
            StreamReader sr2 = new StreamReader(file2);
            string strLine2 = sr2.ReadToEnd();
            // 关闭文件
            sr2.Close();
            file2.Close();
            //第二部 json文件转换成model

            try {
                List<Mapper> mapperlist = new List<Mapper>();
                mapperlist = JsonstringtoList(strLine);
                recordlist = JsonstringtoList2(strLine2);
                if (mapperlist.Count != 0) {
                    foreach (var map in mapperlist) {
                        foreach (var item in recordlist) {
                            if (item.TableRecord.TableName == "TestInfoBaseSerialNo" && map.TargetTable.Name == "RESULTS_HEADER") {
                                StartMapping(map, item);
                            }
                            if (item.TableRecord.TableName == "TestConditionResult" && map.TargetTable.Name == "ESTX_RESULTS_PARAMS") {
                                StartMapping2(map, item);
                            }

                        }

                        var jsonstr = toJson(recordlist);
                        CreateFile(jsonstr);
                    }
                }
                //第三部保存配置文件
                StartKiller();
                MessageBox.Show("导入成功", "MessageBox");


            } catch (Exception err) {
                StartKiller();
                MessageBox.Show("" + err);
            }

            #endregion



        }
        #endregion

        #region 开始根据匹配规则导入数据库

        public void StartMapping2(Mapper mapper, Record record) {
            try {
                DateTime now = DateTime.Now;

                //源数据表
                string sourcetabelname = mapper.SourceTable.Name;

                string targertablename = mapper.TargetTable.Name;


                List<Field> soucrefield = new List<Field>();
                List<Field> targidfiled = new List<Field>();

                List<int> FildKey = new List<int>();
                if (mapper.TargetTable.Fields.Count != 0) {
                    foreach (var item in mapper.TargetTable.Fields) {
                        FildKey.Add(item.Key);
                    }
                }

                foreach (var item in mapper.SourceTable.Fields) {
                    if (FildKey.Contains(item.Key)) {
                        soucrefield.Add(item);

                        foreach (var item2 in mapper.TargetTable.Fields) {
                            if (item2.Key == item.Key) {
                                targidfiled.Add(item2);
                                break;
                            }
                        }

                    }
                }

                int num1 = soucrefield.Count;
                DataTable dt2 = new DataTable();


                //DateTime time = DateTime.Now;
                DateTime time = new DateTime(2016, 12, 21);

                string Path = mapper.SourcePath + time.Year + "-" + time.Month + "-" + time.Day + ".mdb";

                string Pathstring = "testdata@" + time.Year + "-" + time.Month + "-" + time.Day;

                if (Pathstring != record.FileName) {
                    record.FileName = Pathstring;
                    record.TableRecord.RecordNumber = 0;
                }


                OleDbConnection conn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source=" + Path);
                conn.Open();

                #region //ESTX_RESULTS_PARAMS 表导入
                if (mapper.TargetTable.Name == "ESTX_RESULTS_PARAMS") {

                    string sql = "select * from " + mapper.SourceTable.Name;
                    OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
                    DataTable dt = new DataTable();
                    var f = dt.Columns.Count;
                    da.Fill(dt);

                    conn.Close();

                    mainWindowController.ConnecteDatabase(mapper.TargetDb);//连接目标数据库
                    dt2 = mainWindowController.GetFieldDataTable(mapper.TargetTable.Name);


                    if (this.targerDbGroup.Table.Name != null) {
                        var result = false;
                        int queryNumber;
                        if (record.TableRecord.RecordNumber == 0) {
                            queryNumber = 0;
                        } else {
                            queryNumber = record.TableRecord.RecordNumber + 1;
                        }
                        for (int i = queryNumber; i < dt.Rows.Count; i++) {


                            string tablestring2 = GetInsertSql(targidfiled);

                            if (mapper.DefaultValue.Count != 0) {
                                for (int dv = 0; dv < mapper.DefaultValue.Count; dv++) {

                                    tablestring2 += "," + mapper.DefaultValue[dv].Name;

                                }
                            }


                            string dataname = "";
                            bool iscan = false;// 能否插入目标表
                            for (int j = 0; j < num1; j++) {
                                string sourcevalue = soucrefield[j].Name;

                                if (j == 0) {
                                    //找到SEQ_NO
                                    var seqnumber = sqlHelper.GetMaxNumber("select max(SEQNO) as SEQNO from RESULTS_HEADER where BARCODE=" + "'" + dt.Rows[i]["SerialNo"] + "'", "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");
                                    int seqnumber2;
                                    if (seqnumber is DBNull) {
                                        seqnumber2 = 0;
                                        result = false;

                                    } else {
                                        seqnumber2 = Convert.ToInt32(seqnumber);
                                        iscan = true;
                                        //查询该表中是否存在该记录
                                        var resultSEQNO = sqlHelper.CheckBarCode("if exists(select * from  ESTX_RESULTS_HEADER where SEQ_NO='" + seqnumber2 + "') select '1' else select '0'  ", "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");
                                        if (Convert.ToInt32(resultSEQNO) == 1) {
                                            result = true;
                                        } else {
                                            string ESTstr = "INSERT INTO ESTX_RESULTS_HEADER (SEQ_NO, TEST_DURATION, DEVICE_NO, DEVICE_IP, DEVICE_NAME, SERVER)VALUES(" + seqnumber2 + "," + dt.Rows[i]["TestTime"] + " , ' ', '22', ' ', '0')";
                                            sqlHelper.ExecuteSql(ESTstr, "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");
                                            result = true;

                                        }

                                    }                             
                                    dataname += string.Format("'{0}'", seqnumber2);
                                } else {
                                    dataname += string.Format("," + "'{0}'", dt.Rows[i][sourcevalue]);
                                }

                            }

                            #region  //拼接默认值

                            if (mapper.DefaultValue.Count != 0) {
                                for (int dv2 = 0; dv2 < mapper.DefaultValue.Count; dv2++) {

                                    dataname += "," + "'" + mapper.DefaultValue[dv2].DefaultValue + "'";

                                }
                            }

                            #endregion


                            #region //insert into  1
                            if (dt.Rows[i]["TIID"].ToString() == "1"&&result==true) {
                                for (int z = 0; z < 4; z++) {
                                    var datename2 = "";
                                    var tablestring3 = "";
                                    if (z == 0) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "14" + "," + "5" + "," + dt.Rows[i]["ConditionSet"]+","+0;

                                    }
                                    if (z == 1) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "15" + "," + "5" + "," + dt.Rows[i]["ResultValue"] + "," + 0;

                                    }
                                    if (z == 2) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "7" + "," + "20" + "," + dt.Rows[i]["ResultMin"] + "," + 0;

                                    }
                                    if (z == 3) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "8" + "," + "13" + "," + dt.Rows[i]["ResultMax"] + "," + 0;

                                    }

                                    string sqlstr = string.Format("insert into {0} ({1}) values({2})", targertablename, tablestring3, datename2);

                                    try {
                                        sqlHelper.ExecuteSql(sqlstr, "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");
                                    }
                                    catch(Exception err) {
                                        var err1 = err;
                                    }




                                }
                            }
                            #endregion

                            #region //insert into  2
                            if (dt.Rows[i]["TIID"].ToString() == "2" && result == true) {
                                for (int z = 0; z < 4; z++) {
                                    var datename2 = "";
                                    var tablestring3 = "";
                                    if (z == 0) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "1" + "," + "20" + "," + dt.Rows[i]["ConditionSet"] + "," + 1;

                                    }
                                    if (z == 1) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "11" + "," + "34" + "," + dt.Rows[i]["ResultValue"] + "," + 1;

                                    }
                                    if (z == 2) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "4" + "," + "22" + "," + dt.Rows[i]["ResultMin"] + "," + 1;

                                    }
                                    if (z == 3) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "5" + "," + "15" + "," + (Convert.ToDouble(  dt.Rows[i]["ResultMax"])*1000) + "," + 3;

                                    }

                                    string sqlstr = string.Format("insert into {0} ({1}) values({2})", targertablename, tablestring3, datename2);

                                    try {
                                        sqlHelper.ExecuteSql(sqlstr, "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");
                                    } catch (Exception err) {
                                        var err1 = err;
                                    }



                                }
                            }
                            #endregion


                            #region //insert into  3
                            if (dt.Rows[i]["TIID"].ToString() == "3" && result == true) {
                                for (int z = 0; z < 4; z++) {
                                    var datename2 = "";
                                    var tablestring3 = "";
                                    if (z == 0) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "4" + "," + "40" + "," + dt.Rows[i]["ConditionSet"] + "," + 2;

                                    }
                                    if (z == 1) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "13" + "," + "34" + "," + dt.Rows[i]["ResultValue"] + "," + 2;

                                    }
                                    if (z == 2) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "7" + "," + "22" + "," + dt.Rows[i]["ResultMin"] + "," + 2;

                                    }
                                    if (z == 3) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "8" + "," + "15" + "," + (Convert.ToDouble(dt.Rows[i]["ResultMax"]) / 1000000) + "," + 2;

                                    }

                                    string sqlstr = string.Format("insert into {0} ({1}) values({2})", targertablename, tablestring3, datename2);

                                    try {
                                    sqlHelper.ExecuteSql(sqlstr, "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");
                                    }
                                    catch(Exception eror) {
                                        var err001 = eror;
                                    }



                                }
                            }
                            #endregion

                            #region //insert into  4
                            if (dt.Rows[i]["TIID"].ToString() == "4" && result == true) {
                                for (int z = 0; z < 4; z++) {
                                    var datename2 = "";
                                    var tablestring3 = "";
                                    if (z == 0) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "12" + "," + "50" + "," + dt.Rows[i]["ConditionSet"] + "," + 3;

                                    }
                                    if (z == 1) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "9" + "," + "5" + "," + dt.Rows[i]["ResultValue"] + "," + 3;

                                    }
                                    if (z == 2) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "1" + "," + "21" + "," + dt.Rows[i]["ResultMin"] + "," + 3;

                                    }
                                    if (z == 3) {
                                        tablestring3 = tablestring2 + ",PARAM_NO,PARAM_TYPE,PARAM_VALUE,STEP_NO";
                                        datename2 = dataname + "," + "2" + "," + "13" + "," + (Convert.ToDouble(dt.Rows[i]["ResultMax"])) + "," + 3;

                                    }

                                    string sqlstr = string.Format("insert into {0} ({1}) values({2})", targertablename, tablestring3, datename2);

                                    try { 
                                    sqlHelper.ExecuteSql(sqlstr, "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");
                                    } catch (Exception err){
                                        var err1 = err;
                                    }



                                }
                            }
                            #endregion
                        }
                        record.TableRecord.RecordNumber = dt.Rows.Count;
                    }

                }
                #endregion


            } catch (Exception errmes) {
                StartKiller();
                MessageBox.Show("" + errmes);
            }



        }
        public void StartMapping(Mapper mapper, Record record) {
            try {
                DateTime now = DateTime.Now;

                //源数据表
                string sourcetabelname = mapper.SourceTable.Name;

                string targertablename = mapper.TargetTable.Name;


                List<Field> soucrefield = new List<Field>();
                List<Field> targidfiled = new List<Field>();

                List<int> FildKey = new List<int>();
                if (mapper.TargetTable.Fields.Count != 0) {
                    foreach (var item in mapper.TargetTable.Fields) {
                        FildKey.Add(item.Key);
                    }
                }

                foreach (var item in mapper.SourceTable.Fields) {
                    if (FildKey.Contains(item.Key)) {
                        soucrefield.Add(item);

                        foreach (var item2 in mapper.TargetTable.Fields) {
                            if (item2.Key == item.Key) {
                                targidfiled.Add(item2);
                                break;
                            }
                        }

                    }
                }

                int num1 = soucrefield.Count;
                DataTable dt2 = new DataTable();


                //DateTime time = DateTime.Now;
                DateTime time = new DateTime(2016, 12, 21);

                string Path = mapper.SourcePath + time.Year + "-" + time.Month + "-" + time.Day + ".mdb";

                string Pathstring = "testdata@" + time.Year + "-" + time.Month + "-" + time.Day;

                if (Pathstring != record.FileName) {
                    record.FileName = Pathstring;
                    record.TableRecord.RecordNumber = 0;
                }


                OleDbConnection conn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source=" + Path);
                conn.Open();

                #region // RESULTS_HEADER 表导入
                if (mapper.TargetTable.Name == "RESULTS_HEADER") {
                    string sql = "select * from " + mapper.SourceTable.Name;
                    OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
                    DataTable dt = new DataTable();
                    var f = dt.Columns.Count;
                    da.Fill(dt);

                    conn.Close();

                    mainWindowController.ConnecteDatabase(mapper.TargetDb);//连接目标数据库
                    dt2 = mainWindowController.GetFieldDataTable(mapper.TargetTable.Name);


                    if (this.targerDbGroup.Table.Name != null) {
                        int queryNumber;
                        if (record.TableRecord.RecordNumber == 0) {
                            queryNumber = 0;
                        } else {
                            queryNumber = record.TableRecord.RecordNumber + 1;
                        }
                        for (int i = queryNumber; i < dt.Rows.Count; i++) {

                            string tablestring2 = GetInsertSql(targidfiled);

                            if (mapper.DefaultValue.Count != 0) {
                                for (int dv = 0; dv < mapper.DefaultValue.Count; dv++) {

                                    tablestring2 += "," + mapper.DefaultValue[dv].Name;

                                }
                            }
                            tablestring2 += "," + "FAILCODE" + ","+"STATUS"+"," + "SEQNO";

                            string dataname = "";
                            for (int j = 0; j < num1; j++) {

                                string sourcevalue = soucrefield[j].Name;

                                if (j == 0) {



                                    dataname += string.Format("'{0}'", dt.Rows[i][sourcevalue]);
                                } else {
                                    dataname += string.Format("," + "'{0}'", dt.Rows[i][sourcevalue]);
                                }

                            }

                            //拼接后面的值
                            if (mapper.DefaultValue.Count != 0) {
                                for (int dv2 = 0; dv2 < mapper.DefaultValue.Count; dv2++) {

                                    dataname += "," + "'" + mapper.DefaultValue[dv2].DefaultValue + "'";

                                }
                            }


                            if (dt.Rows[i]["TestResult"].ToString() == "PASS") {
                                dataname += "," + "'" + 100 + "'"+",1";
                            } else {
                                dataname += "," + "'" + 0 + "'"+",0";
                            }

                            var seqnumber = sqlHelper.GetMaxNumber("select max(SEQNO) as SEQNO from RESULTS_HEADER", "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");
                            int seqnumber2 = Convert.ToInt32(seqnumber) + 1;
                            dataname += "," + "'" + seqnumber2 + "'";



                            //查询该表中是否存在该记录
                            var result = sqlHelper.CheckBarCode("if exists(select * from  RESULTS_HEADER where BARCODE='" + dt.Rows[i][soucrefield[0].Name] + "') select '1' else select '0'  ", "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");


                            //存在就添加
                            if (Convert.ToInt32(result) == 1) {
                                tablestring2 = tablestring2 + "," + "MODEL_ID" + "," + "DATE_TESTED";

                                string modelID = GetModelId(dt.Rows[i][soucrefield[0].Name].ToString(), "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");

                                dataname = dataname + "," + "'" + modelID + "'" + "," + "'" + DateTime.Now + "'";



                                string sqlstr = string.Format("insert into {0} ({1}) values({2})", targertablename, tablestring2, dataname);

                                sqlHelper.ExecuteSql(sqlstr, "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");

                                record.TableRecord.RecordNumber = dt.Rows.Count;
                            } else {
                                StartKiller();
                                //MessageBox.Show("PLIS中不存在该Barcode:" + dt.Rows[i][soucrefield[0].Name]);
                            }
                            //存在就更新
                            //else {
                            //    var stringZ = "";
                            //    for (int m = 1; m < targidfiled.Count(); m++) {
                            //        if (m == targidfiled.Count() - 1)
                            //            stringZ += targidfiled[m].Name + "=" + "'" + dt.Rows[i][soucrefield[m].Name] + "'";
                            //        else
                            //            stringZ += targidfiled[m].Name + "=" + "'" + dt.Rows[i][soucrefield[m].Name] + "'" + ",";
                            //    }

                            //    string sqlString = string.Format("update {0} set {1}where " + contions + "", targertablename, stringZ);

                            //    sqlHelper.ExecuteSql(sqlString, "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");


                            //}
                        }
                    }

                }
                #endregion

            } catch (Exception errmes) {
                StartKiller();
                MessageBox.Show("" + errmes, "MessageBox");
            }


        }
        #endregion

        #region //得到目标数据表中的要插入的字段
        public string GetInsertSql(List<Field> FildList) {
            string s = "";

            if (FildList.Count != 0) {
                for (int i = 0; i < FildList.Count; i++) {
                    if (i == 0) {
                        s += FildList[i].Name;
                    } else {
                        s += "," + FildList[i].Name;
                    }
                }
            }

            return s;
        }
        #endregion


        #region //得到Update SQL 语句
        public string UpdateString() {
            string sql = "";

            return sql;

        }
        #endregion

        #region //将json 数据转换成model
        public List<Mapper> JsonstringtoList(string jsonstr) {
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            var objs = Serializer.Deserialize<List<Mapper>>(jsonstr);
            return objs;
        }
        public List<Record> JsonstringtoList2(string jsonstr) {
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            var objs = Serializer.Deserialize<List<Record>>(jsonstr);
            return objs;
        }
        #endregion

        #region//暂停定时器
        //private void btn_push_Click(object sender, EventArgs e)
        //{
        //    if (myTimer.Enabled)
        //    {
        //        myTimer.Enabled = false; //定时器停止
        //        btn_push.Text = "继续";
        //    }
        //    else
        //    {
        //        myTimer.Enabled = true;
        //        btn_push.Text = "暂停";
        //    }
        //}
        #endregion

        #region //点击关闭定时器
        private void btn_close_Click(object sender, EventArgs e) {
            myTimer.Close(); //释放Timer占用的资源
            myTimer.Dispose();
            btn_Import.Visible = true;
            btn_close.Visible = false;
            foreach (TabPage page in tabControls.TabPages) {
                foreach (Control control in page.Controls) {
                    if (control is RichTextBox) {
                        ((RichTextBox)control).ReadOnly = false;

                    }
                }
            }
        }
        #endregion

        #region  //定时器输入格式限制
        private void tb_inputtime_KeyPress(object sender, KeyPressEventArgs e) {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8) {
                e.Handled = true;//经过判断为数字，可以输入
            }

        }
        #endregion


        //保存修改后规则
        private void btn_addPage_Click(object sender, EventArgs e) {
            int pagenumber = 0;
            foreach (TabPage page in tabControls.TabPages) {
                foreach (Control control in page.Controls) {
                    pagenumber++;
                    if (control is RichTextBox && pagenumber == 1) {

                        string value = ((RichTextBox)control).Text;
                        CreateFile2(value);

                    } else {

                        string value = ((RichTextBox)control).Text;
                        CreateFile(value);

                    }
                }
            }
            StartKiller();
            MessageBox.Show("保存成功", "MessageBox");
        }





        //List 转换成json
        public string toJson(List<Record> recordlist) {
            DataContractJsonSerializer json = new DataContractJsonSerializer(recordlist.GetType()); //获取数据类型
            string jsonStr = "";
            using (MemoryStream stream = new MemoryStream()) {
                json.WriteObject(stream, recordlist);
                jsonStr = Encoding.UTF8.GetString(stream.ToArray());
            }
            return jsonStr;
        }


        //讲JSON文件保存到TXT
        public void CreateFile(string jsonstring) {
            string path = AppDomain.CurrentDomain.BaseDirectory + "reocrd.txt";
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite); //可以指定盘符，也可以指定任意文件名，还可以为word等文件
            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8); // 创建写入流
            fs.SetLength(0);
            sw.WriteLine(jsonstring); // 写入Hello World
            sw.Close(); //关闭文件
        }

        public void CreateFile2(string jsonstring) {
            string path = AppDomain.CurrentDomain.BaseDirectory + "mapper.txt";

            FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite); //可以指定盘符，也可以指定任意文件名，还可以为word等文件
            fs.SetLength(0);
            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8); // 创建写入流
            sw.WriteLine(jsonstring); // 写入Hello World
            sw.Close(); //关闭文件
        }

        private void ckBox_CheckedChanged(object sender, EventArgs e) {
            if (ckBox.Checked) {
                MessageBox.Show("设置开机自启动，需要修改注册表", "提示");
                string path = Application.ExecutablePath;
                RegistryKey rk = Registry.CurrentUser;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rk2.SetValue("JcShutdown", path);
                rk2.Close();
                rk.Close();
            } else {
                MessageBox.Show("取消开机自启动，需要修改注册表", "提示");
                string path = Application.ExecutablePath;
                RegistryKey rk = Registry.CurrentUser;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rk2.DeleteValue("JcShutdown", false);
                rk2.Close();
                rk.Close();
            }
        }

        //private void checkBox1_CheckedChanged(object sender, EventArgs e) {

        //    if (checkBox1.Checked) //设置开机自启动  
        //                {
        //        MessageBox.Show("设置开机自启动，需要修改注册表", "提示");
        //        string path = Application.ExecutablePath;
        //        RegistryKey rk = Registry.CurrentUser;
        //        RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
        //        rk2.SetValue("JcShutdown", path);
        //        rk2.Close();
        //        rk.Close();
        //    } else //取消开机自启动  
        //      {
        //        MessageBox.Show("取消开机自启动，需要修改注册表", "提示");
        //        string path = Application.ExecutablePath;
        //        RegistryKey rk = Registry.CurrentUser;
        //        RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
        //        rk2.DeleteValue("JcShutdown", false);
        //        rk2.Close();
        //        rk.Close();
        //    }

        //}



        private void StartKiller() {
            Timer timer = new Timer();
            timer.Interval = 3000; //3秒启动 
            timer.Tick += new EventHandler(Timer_Tick);
            timer.Start();
        }
        private void Timer_Tick(object sender, EventArgs e) {
            KillMessageBox();
            //停止Timer 
            ((Timer)sender).Stop();
        }
        private void KillMessageBox() {
            //按照MessageBox的标题，找到MessageBox的窗口 
            IntPtr ptr = FindWindow(null, "MessageBox");
            if (ptr != IntPtr.Zero) {
                //找到则关闭MessageBox窗口 
                PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            }
        }
        //返回modeId
        public string GetModelId(string barcode, string strcon) {
            string sql = "SELECT  MODEL_ID FROM RESULTS_HEADER WHERE  BARCODE = '" + barcode + "'";

            DataTable dt = sqlHelper.GetModelIDTable(sql, strcon);

            return dt.Rows[0]["Model_ID"].ToString();

        }


    }
}


